define([ './module' ], function(module) {
	'use strict';

	module.controller('communitycirclearticle',servercommunitycirclearticlectrl);
	function servercommunitycirclearticlectrl($stateParams,$http,$location,$scope,Upload,$timeout){


		//查询所有社区圈子
		$scope.findallcommunitycircle=function(){
			$http({
				method:'POST',
				url:'../mall/communitycircle/findAll'
			}).
			success(function(data,status,headers,config){
				if(data.sucflag){
					$scope.communitycircleselect =data.beanlist;
					$scope.selectedcommunitycircle="-1";
				}
			}).
			error(function(data,status,headers,config){
				$scope.errors={
					show:true,
					msg:'系统异常'
				}
			});
		}


		$scope.$watch('allrfiles', function () {
			$scope.uploadrmainfiles($scope.rmainfiles);
		});
		$scope.allrfiles = [];
		$scope.uploadrmainfiles = function (files) {
			if (files && files.length) {
				for (var i = 0; i < files.length; i++) {
					var file = files[i];
					var filename = files[i].name;
					if (!file.$error) {
						Upload.upload({
							url: '../mall/files/ajaxFileUploadsImgs',
							data: {
								file: file,
								filename: filename
							}
						}).progress(function (evt) {
							var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
							$scope.rmainprogress = progressPercentage;
						}).success(function (data, status, headers, config) {
							$timeout(function () {
								if (data.ifb.sucflag) {
									$scope.allrfiles.push(data.ifb);
								}
							});
						});
					}
				}
			}
		}

		$scope.removeallrmainfiles = function (index) {
			$scope.allrfiles.splice(index, 1);
		}


		//通过location中的operate参数区分操作行为
		var operate = $location.search().operate||$stateParams.operate;
		if (operate != undefined && operate == "save") {
			//控制保存按钮显示
			$scope.savebtn = {show: true};
			$scope.title = '添加社区圈子文章';
			//设置启用 1表示启用
			$scope.status = "1";
			$scope.communitycircleshow=true;
			$scope.lastcommunitycircleshow=false;
			$scope.modifylastcommunitycircleshow=false;

			$scope.save = function () {
				if($scope.selectedcommunitycircle==undefined){
					$scope.errors = {
						show: true,
						msg: '请选择所属社区圈子'
					}
					return false;
				}
				if ($scope.ctitle == undefined) {
					$scope.errors = {
						show: true,
						msg: '请输入标题'
					}
					return false;
				}

				if ($scope.contentvalue == undefined) {
					$scope.errors = {
						show: true,
						msg: '请输入正文'
					}
					return false;
				}

				$http({
					method: 'POST',
					url: '../mall/communitycirclearticle/save',
					data: {
						"communitycircleid":$scope.selectedcommunitycircle.id,
						"communitycirclename":$scope.selectedcommunitycircle.name,
						"ctitle": $scope.ctitle,
						"contentvalue": $scope.contentvalue,
						"imgs": angular.toJson($scope.allrfiles),
						"status": $scope.status
					}
				}).success(function (data, status, headers, config) {
						if (data.sucflag) {
							$scope.errors = {};
							$scope.info = {
								show: true,
								msg: '社区圈子文章添加成功'
							}
							$location.path('/communitycirclearticlement');
						}
					}).error(function (data, status, headers, config) {
					$scope.errors = {
						show: true,
						msg: '系统异常'
					}
				});

			}
		}

		if (operate == 'edit') {
			var id = $location.search().id;
			if (id != undefined && id != "") {
				$http({
					method: 'POST',
					url: '../mall/communitycirclearticle/find',
					data: {
						'id': id
					}
				}).success(function (data, status, headers, config) {
					if (data.sucflag) {
						$scope.title = '正在对--' + data.bean.ctitle + '--进行编辑';
						$scope.lastcommunitycirclename=data.bean.communitycirclename;
						$scope.communitycircleid=data.bean.communitycircleid;
						$scope.ctitle = data.bean.ctitle;
						$scope.status = data.bean.status;
						$scope.contentvalue = data.bean.contentvalue;
						$scope.allrfiles = data.ifbs;
						$scope.lastcommunitycircleshow=true;
						$scope.modifylastcommunitycircleshow=true;
						$scope.updatebtn = {show: true};
					}
				}).error(function (data, status, headers, config) {
					$scope.errors = {
						show: true,
						msg: '系统异常'
					}
				});
			}

			//点击分类
			$scope.clickmodifycommunitycircle = function () {
				$scope.communitycircleshow = true;
			}

			$scope.update = function () {

				var communitycircleid= "";
				var communitycirclename = "";
				if ($scope.communitycircleshow) {
					if ($scope.selectedcommunitycircle == undefined) {
						$scope.errors = {
							show: true,
							msg: '请选择社区圈子'
						}
						return false;
					} else {
						communitycircleid = $scope.selectedcommunitycircle.id;
						communitycirclename = $scope.selectedcommunitycircle.name;
					}
				} else {
					communitycircleid = $scope.communitycircleid;
					communitycirclename = $scope.lastcommunitycirclename;
				}

				if ($scope.ctitle == undefined) {
					$scope.errors = {
						show: true,
						msg: '请输入标题'
					}
					return false;
				}

				if ($scope.contentvalue == undefined) {
					$scope.errors = {
						show: true,
						msg: '请输入正文'
					}
					return false;
				}

				$http({
					method: 'POST',
					url: '../mall/communitycirclearticle/update',
					data: {
						"communitycircleid":communitycircleid,
						"communitycirclename":communitycirclename,
						"ctitle": $scope.ctitle,
						"author": $scope.author,
						"contentvalue": $scope.contentvalue,
						"imgs": angular.toJson($scope.allrfiles),
						"status": $scope.status,
						"id": id
					}
				})
					.success(function (data, status, headers, config) {
						if (data.sucflag) {
							$scope.errors = {};
							$scope.info = {
								show: true,
								msg: '更新成功'
							}
							$location.path('/communitycirclearticlement');
						}
					}).error(function (data, status, headers, config) {
					$scope.errors = {
						show: true,
						msg: '系统异常'
					}
				});

			}
		}
	}


	module.controller('communitycirclearticlement',servercommunitycirclearticlementctrl);
	//查询列表数据
	function servercommunitycirclearticlementctrl($http,$location,$compile,$scope,DTOptionsBuilder,DTColumnBuilder){
		$scope.title="社区圈子文章列表";
		var vm=this;
		vm.message='';
		vm.someClickHandler = someClickHandler;
		vm.selected={};
		vm.selectAll=false;
		vm.toggleAll=toggleAll;
		vm.toggleOne=toggleOne;
		vm.dtInstance={};
		var titleHtml='<input type="checkbox" ng-model="showCase.selectAll" ng-click="showCase.toggleAll(showCase.selectAll,showCase.selected)">';
		vm.dtOptions=DTOptionsBuilder.newOptions().withOption('ajax',{
			type:'POST',
			url:'../mall/communitycirclearticle/findByPage',
			dataSrc:'data'
		})
		.withOption('processing',true)
		.withOption('paging',true)
		.withOption('serverSide',true)
		.withOption('createdRow',function(row,data,dataIndex){
			$compile(angular.element(row).contents())($scope);
		})
		.withOption('headerCallback', function(header) {
            if (!$scope.headerCompiled) {
                $scope.headerCompiled = true;
                $compile(angular.element(header).contents())($scope);
            }
        })
        .withOption('stateSave', true)
        .withOption('rowCallback',rowCallback)
		.withPaginationType('full_numbers')
		.withLanguageSource('./app/language/chinese.json')

		$scope.$on('handleRequest',function(){

		});
		vm.dtColumns=[
		              DTColumnBuilder.newColumn(null).withTitle(titleHtml).notSortable().renderWith(function(data,type,full,meta){
		            	  vm.selected[full.id]=false;
		            	  return "<input type='checkbox' ng-model=\"showCase.selected['"+data.id+"']\" ng-click=\"showCase.toggleOne(showCase.selected)\">";
		              }),
		              DTColumnBuilder.newColumn('id').withTitle('ID').notVisible(),
			          DTColumnBuilder.newColumn('ctitle').withTitle('标题').notSortable(),
			          DTColumnBuilder.newColumn('communitycirclename').withTitle('社区圈子').notSortable(),
			          DTColumnBuilder.newColumn('reviewed').withTitle('审核').notSortable(),
			          DTColumnBuilder.newColumn('status').withTitle('状态').notSortable(),
			          DTColumnBuilder.newColumn('updatetime').withTitle('更新时间').notSortable(),
			          DTColumnBuilder.newColumn('version').withTitle('版本号').notSortable(),
			          DTColumnBuilder.newColumn(null).withTitle('操作').notSortable().renderWith(actionHtml)];

		function actionHtml(data,type,full,meta){
			return "<button  ng-click=\"edit('"+data.id+"')\" class='btn btn-warning'><i class='fa fa-edit'></i></button>"+
			"<button ng-click=\"singalcommunitycircletitlecommentment('"+data.id+"','"+data.ctitle+"')\" class='btn btn-success'><i class='fa fa-comments-o'></i></button>";
		}

		function reloadData(){
			var resetPaging = false;
	        vm.dtInstance.reloadData(callback, resetPaging);
		}
		function callback(data){
		}


		/**
		 * 复杂搜索刷新数据
		 */
		function searchReloadData(){
			var resetPaging=false;
			var searchParams={
				isCustomSearch:1,
				name:''
			};
			if($scope.goodsname!=undefined){
				searchParams.name=$scope.goodsname;
				vm.dtOptions['ajax'].data=searchParams;
				vm.dtInstance.reloadData(callback, resetPaging);
			}
		}

		/**
		 * 表格
		 */
		$scope.searchdataTableCustom=function(){
			searchReloadData();
		}


		/**
		 * 跳转进入单个社区圈子文章评论列表
		 * @param id
		 * @param name
		 */
		$scope.singalcommunitycircletitlecommentment=function(id,name){
			$location.path('/communitycirclearticlecommentonement').search({'operate':'find','id':id,'communitycirclearticletitle':name});
		}

		//表格中编辑按钮
		$scope.edit=function(id,name){
			$location.path('/communitycirclearticle').search({'operate':'edit','id':id});
		}


		/**
		 * 跳转到添加商品类型和参数页面
		 */
		$scope.save=function(){
			$location.path('/communitycirclearticle').search({'operate':'save'});
		}

		$scope.del=function(){
			var i=0;
			var ids=[];
			angular.forEach(vm.selected, function(data,index,array){
				if(data){
					i++;
					ids.push(index);
				}
			});
			if(i==0){
				$scope.errors={
						show:true,
						msg:'请选择一条记录'
				}
			}else{
				$scope.errors={
						show:false
				}
				//批量删除数据
				var idstrs=ids.join(",");
				$http({
					method:'POST',
					url:'../mall/communitycirclearticle/del',
					data:{
						'id':idstrs
					}
				}).
				success(function(data,status,headers,config){
					if(data.sucflag){
						$scope.errors={};
						$scope.info={
								show:true,
								msg:'删除成功'
						}
						reloadData();
					}

				}).
				error(function(data,status,headers,config){
					$scope.errors={
							show:true,
							msg:'系统异常'
					}
				});
			}
		}

		/**
		 * 列表全选
		 */
		function toggleAll(selectAll,selectedItems){
			for(var id in selectedItems){
				if(selectedItems.hasOwnProperty(id)){
					selectedItems[id]=selectAll;
				}
			}
		}
		/**
		 * 列表单选
		 */
		function toggleOne(selectedItems){
			var me=this;
			for(var id in selectedItems){
				if(selectedItems.hasOwnProperty(id)){
					if(!selectedItems[id]){
						me.selectAll=false;
					}
				}
			}
			me.selectAll=true;

		}

		function someClickHandler(info) {
	        vm.message = info.id + ' - ' + info.name;

	    }
		/**
		 * 单击列表某行回调
		 */
		function rowCallback(nRow,aData,iDisplayIndex,iDisplayIndexFull){
			$('td', nRow).unbind('click');
	        $('td', nRow).bind('click', function() {
	            $scope.$apply(function() {
	                vm.someClickHandler(aData);

	            });
	        });
	        return nRow;
		}

	}
});
